package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.config.RedissonConfig;
import com.hmdp.dto.Result;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherMapper;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import io.lettuce.core.RedisClient;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private IVoucherOrderService voucherOrderService;


    @Resource
    private  StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisIdWorker redisIdWorker;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("can_seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //异步处理线程池
    private static  final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    private IVoucherService proxy;
//    // 阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks =new ArrayBlockingQueue<>(1024 * 1024);

    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    // 用于线程池处理的任务
    // 当初始化完毕后，就会去从对列中去拿信息
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    handleFromRedisMQ();
                } catch (Exception e) {
                    log.error("处理订单异常,从pending-list重新处理", e);
                    handlePendingList();
                }
            }
        }

        private  void handleFromRedisMQ(){
            // 从redis消息队列中获取队列中的订单信息
            // XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 >
            List<MapRecord<String, Object, Object>> orderList = stringRedisTemplate.opsForStream().read(
                    // 消费者的组名，以及成员名
                    Consumer.from("g1", "c1"),
                    // 堵塞消费一个，最多阻塞2秒
                    StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                    // 队列名，ReadOffset.lastConsumed()指定">",也就是消息队列的头
                    StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
            );
            if( orderList == null || orderList.size() <= 0) return;

            // 解析数据

            Map<Object, Object> order = orderList.get(0).getValue();
            for (Map.Entry<Object, Object> objectObjectEntry : order.entrySet()) {
                System.out.println("objectObjectEntry = " + objectObjectEntry);
            }
            VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(order, new VoucherOrder(), true);

            System.out.println("voucherOrder = " + voucherOrder);
            // 创建订单
            handleVoucherOrder(voucherOrder);

            // 发送确认消息
            stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1",orderList.get(0).getId());
        }
        private void handlePendingList(){
            while (true) {
                try {
                    // 获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            // 这里不再需要阻塞式的获取
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );

                    // 判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有异常消息，结束循环
                        break;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pendding订单异常", e);
                    try{
                        Thread.sleep(2);
                    }catch(Exception e1){
                        e1.printStackTrace();
                    }
                }
            }
        }
        private void handleVoucherOrder(VoucherOrder voucherOrder) {

            Long userId = voucherOrder.getUserId();

            RLock lock = redissonClient.getLock(LOCK_SECKILLVOUCHER + userId);
            boolean isLock = false;
            try {
                isLock = lock.tryLock(1,20, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            //加锁失败
            if (!isLock) {
                // 获取锁失败，直接返回失败或者重试
                log.error("不允许重复下单！");
                return;
            }

            try {
                 proxy.createVoucherOrder(voucherOrder);
            } finally {
                //释放锁
                lock.unlock();
            }
        }
    }

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        // 查询优惠券信息
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
        // 返回结果
        return Result.ok(vouchers);
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());


        // 保存秒杀库存到Redis中
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucher.getStock().toString());
        seckillVoucherService.save(seckillVoucher);
    }

    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {


        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        System.out.println("orderId = " + orderId);
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }

//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);

        //获取代理对象
        proxy = (IVoucherService) AopContext.currentProxy();

        return Result.ok(orderId);

    }



    @Transactional
    public  void createVoucherOrder(VoucherOrder voucherOrder) {

        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();

        // 查询订单
        int count = voucherOrderService.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            log.error("用户已经购买过了");
            return ;
        }

        // 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherId).gt("stock", 0) // where id = ? and stock > 0
                .update();
        if (!success) {
            // 扣减失败
            log.error("库存不足");
            return ;
        }

        voucherOrderService.save(voucherOrder);

    }

//    @Override
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("抢购时间未到。");
//        }
//
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("抢购已结束。");
//        }
//        if (seckillVoucherService.getById(voucherId).getStock() < 1) {
//            return Result.fail("优惠券已经抢完了。");
//        }
//
//
//        Long userId = UserHolder.getUser().getId();
//        RLock lock = redissonClient.getLock(LOCK_SECKILLVOUCHER + userId);
//        boolean isLock = lock.tryLock(1,20, TimeUnit.SECONDS);
//
//        //加锁失败
//        if (!isLock) {
//            return Result.fail("不允许重复下单");
//        }
//
//        try {
//            //获取代理对象(事务)
//            // 获取 代理对象
//            IVoucherService proxy = (IVoucherService) AopContext.currentProxy();
//            return  proxy.createVoucherOrder(voucherId);
//        } finally {
//            //释放锁
//            lock.unlock();
//        }
//
//    }


    @Transactional
    public  Result createVoucherOrder(Long voucherId) {

        Long userId = UserHolder.getUser().getId();

        // 5.1.查询订单
        int count = voucherOrderService.query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 5.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            return Result.fail("用户已经购买过一次！");
        }

        // 6.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherId).gt("stock", 0) // where id = ? and stock > 0
                .update();
        if (!success) {
            // 扣减失败
            return Result.fail("库存不足！");
        }

        // 7.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 7.1.订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 7.2.用户id
        voucherOrder.setUserId(userId);
        // 7.3.代金券id
        voucherOrder.setVoucherId(voucherId);
        voucherOrderService.save(voucherOrder);


        // 7.返回订单id
        return Result.ok(voucherId);
    }


}
